import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import { Drawer, Form, Button, Col, Row, Input, Select, DatePicker, Icon, message, Radio, Tabs, Collapse } from 'antd';
import styles from './typeNode.less';
import Editor from '@/utils/Editor';
import AnswerEdit from './answerEdit';
import AnswerBack from './answerBack';
import axios from 'axios';
import UserSession from "@/UserSession";
const TabPane = Tabs.TabPane;
const { TextArea } = Input;
const { Panel } = Collapse;
class Answer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      answerArr: [
        {
          isDefault: true,
          content: props.quoteAnswerObj ? props.quoteAnswerObj.answer : '',
          answerType: 'richText',
          slotValues: [],
          isEdit: false,
          slotDetailArr: [],
          answerQuestion: null,
          id: null,
          relAnswerId: null,
        },
      ],
      answerArr_bak: [
        {
          isDefault: true,
          content: '',
          answerType: 'richText',
          slotValues: [],
          isEdit: false,
          answerQuestion: null,
          id: null,
          relAnswerId: null,
        },
      ],
      qaActiveKeys: [],
      slotArr: [],
      slotDetailArr: [],
      conRefs: [],
    };
  }

  componentDidMount() {
    this.setState({ slotArr: this.props.slotArr });
    this.props.onRef(this);
  }

  componentWillReceiveProps() {
    this.setState({ slotArr: this.props.slotArr });
  }

  setAnswer = data => {
    console.log(data);
    let { answerArr } = this.state;
    for (let i of answerArr) {
      if (i.isDefault) {
        i.content = data.answer;
        i.answerQuestion = data.question;
        i.relAnswerId = data.id;
        i.isEdit = true;
        i.answerType = 'richText'
      }
    };

    this.setState({ answerArr, answerArr_bak: answerArr });
  };

  getAnswer(data) {
    this.setState({ spinning: false, answerArr: data, answerArr_bak: data });
  }

  callback(key, index) {
    const arr = this.state.answerArr;
    arr[index].answerType = key;
    this.setState({ answerArr: arr });
  }

  onEditQa = (index, type, refsCon) => {
    const arr = this.state.answerArr;
    if (index !== -1 && type !== 'save') {
      arr[index].isEdit = !arr[index].isEdit;
      this.setState({ answerArr: arr });
    }
    switch (type) {
      case 'save':
        this.setDefaultAnswer(index, refsCon);
        break;
      case 'del':
        this.delDefaultAnswer(index, 'del');
        break;
      case 'add':
        this.addAnswer();
        break;
      case 'edit':
        this.editAnswer(index);
        break;
      case 'cancel':
        this.delDefaultAnswer(index, 'cancel');
        break;
    }
  };
  editAnswer = index => {
    const slotList = this.state.slotArr;
    for (const i of slotList) {
      this.fetchSlotDetailBySlotId(i._id, i.name, index);
    }
  };
  addAnswer = () => {
    const answers = this.state.answerArr;
    const answer_bak = this.state.answerArr_bak;
    let arr = [];
    let arr_bak = [];
    arr = arr.concat(answers);
    arr_bak = arr_bak.concat(answer_bak);
    arr.unshift({
      isDefault: false,
      content: '',
      answerType: 'richText',
      slotValues: [],
      isEdit: false,
      answerQuestion:null,
      id:null,
      relAnswerId:null
    });
    arr_bak.unshift({
      isDefault: false,
      content: '',
      answerType: 'richText',
      slotValues: [],
      isEdit: false,
      answerQuestion:null,
      id:null,
      relAnswerId:null
    });
    let conIndex = arr.length - 1;

    // arr[0].con = this.AnswerEdit.refs
    const slotList = this.state.slotArr;
    for (const i of slotList) {
      this.fetchSlotDetailBySlotId(i._id, i.name);
    };
    let conArr = this.state.conRefs;
    this.setState({ answerArr: arr, answerArr_bak: arr_bak, qaActiveKeys: [] });
  };
  setDefaultAnswer = (index, refsCon) => {
    const answer = this.state.answerArr;
    const answer_bak = this.state.answerArr_bak;
    const type = answer[index].answerType;
    const slots_bak = answer_bak[index].slotValues;
    const isDefault = answer[index].isDefault;
    answer[index].slotValues = slots_bak;
    const slots = answer[index].slotValues;
    if (slots.length === 0 && !isDefault) {
      return message.error('词槽答案词槽不允许为空，请添加词槽再保存');
    };
    if (slots.length === 1 && !isDefault) {
      for (const i of slots) {
        if (i.values.length == 0) {
          return message.error('词槽答案词槽不允许为空，请添加词槽再保存');
        }
      }
    };
    let content = '';
    const con = refsCon;
    let conArr = this.state.conRefs;
    conArr.push(con);
    this.setState({ cons: conArr });
    switch (type) {
      case 'richText':
        content = con.getUeditorContent();
        break;
      case 'text':
        content = this.state.textValue;
        break;
    };
    answer[index].content = content;
    answer[index].isEdit = !answer[index].isEdit;
    const qaActiveKeys = this.state.qaActiveKeys;
    qaActiveKeys.push(answer.length.toString());
    this.setState({ answerArr: answer, qaActiveKeys });
  };
  delDefaultAnswer = (index, type) => {
    const arr_bak = this.state.answerArr_bak;
    const arr = this.state.answerArr;
    const isDefault = arr_bak[index].isDefault;
    const isEdit = arr_bak[index].isEdit;
    switch (type) {
      case 'del':
        if (!isDefault) {
          arr.splice(index, 1);
          this.setState({ answerArr_bak: arr, answerArr: arr });
        };
        break;
      case 'cancel':
        if (!isDefault) {
          if (!isEdit) {
            arr_bak.splice(index, 1);
            arr.splice(index, 1);
            this.setState({ answerArr_bak: arr_bak, answerArr: arr });
          }
        };
        break;
    }
  };
  callbackFromChild(data) {
    switch (data.funName) {
      case 'onEditQa':
        this.onEditQa(data.index, data.type, data.refsCon);
        break;
      case 'callback':
        this.callback(data.index, data.type);
        break;
      case 'getTextValue':
        this.getTextValue(data.index, data.type);
        break;
    }
  }
  getTextValue = e => {
    const value = e.target.value;
    this.setState({ textValue: value });
  };
  fetchSlotDetailBySlotId = (id, name, index) => {
    const that = this;
    that.setState({ slotDetailArr: [] });

    let dispatch = this.props.props.dispatch;
    const token =
			window.localStorage.getItem("robot_token") == undefined
				? ""
				: window.localStorage.getItem("robot_token");
    const headData = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token };

    axios
      .post('/knowledge-api/knowledge/base/getSlotValues', { slotId: id }, { headers: headData })
      .then(ret => {
        let res = null;
        if (ret.data.data) {
          res = ret.data.data;
        } else {
          res = ret.data;
        }

        res[0].name = name;
        res[0].id = id;
        const arr = that.state.slotDetailArr;
        let newArr = [];
        const result = arr.some(items => {
          return items.name == res[0].name;
        });
        // if(!result){
        newArr = newArr.concat(arr);
        newArr = newArr.concat(res);
        if (index !== undefined) {
          for (const o of that.state.answerArr[index].slotValues) {
            for (const j of newArr) {
              if (o.slotName === j.name) {
                j.values = o.values;
              }
            }
          }
        } else {
          for (const i of that.state.answerArr) {
            for (const o of i.slotValues) {
              for (const j of newArr) {
                if (o.slotName === j.name) {
                  j.values = o.values;
                }
              }
            }
          }
        };
        this.setState({ slotDetailArr: newArr });
      });
  };
  addSlotForSelect = (value, index, slotIndex, _id, newName) => {
    const arr = this.state.answerArr_bak;
    const oldSlotArr = arr[index].slotValues;

    const newArr = oldSlotArr.filter(item => item.slotName === newName);

    if (newArr.length > 0) {
      oldSlotArr[slotIndex].values = value;
    } else {
      oldSlotArr.push({ id: _id, values: value, slotName: newName });
    };
    this.setState({ answerArr_bak: arr });
  };
  toAddSlotForSelect(data) {
    this.addSlotForSelect(data.value, data.index, data.slotIndex, data._id, data.newName);
  };
  editSlotByUnSelect = (value, index) => {
    const arr = this.state.answerArr_bak;
    const slots = arr[index].slotValues;
    slots.forEach(item => {
      item.values.forEach((s, j) => {
        if (s === value) {
          item.values.splice(j, 1);
        }
      });
    });
    this.setState({ answerArr_bak: arr });
  };
  toEditSlotByUnSelect(data) {
    this.editSlotByUnSelect(data.value, data.index);
  };
  toOnEditQa(data) {
    if (data.type === 'save') {
      this.onEditQa(data.index, data.type, data.refsCon);
    } else {
      this.onEditQa(data.index, data.type);
    }
  }

  setSlotDetailArr(data) {
    this.setState({ slotDetailArr: data });
  }

  getRefs() {
    return this.AnswerEdit;
  }

  quoteAnswer = () => {
    this.props.onShow(0);
  };

  deleteQuestionFrom = (index) => {
    let arr = this.state.answerArr;
    arr[index].answerQuestion = null;
    arr[index].relAnswerId = null
    this.setState({ answerArr: arr })
  }

  render() {
    const { answerArr, slotDetailArr, qaActiveKeys } = this.state;
    console.log(answerArr);
    return (
      <div>
        <Row>
          <Col span={4}>
            <div className={styles.label}>答案</div>
          </Col>
          <Col span={4} offset={16}>
            <div>
              {this.state.slotArr.length > 0 ? (
                <Button
                  htmlType="button"
                  style={{ marginLeft: 10 }}
                  type="primary"
                  size="small"
                  icon="plus"
                  onClick={() => this.onEditQa(-1, 'add')}
                >
                  添加答案
                </Button>
              ) : (
                ''
              )}
              {UserSession.isSystemDataKnowledge() ? null : (
                <Button
                  htmlType="button"
                  style={{ marginLeft: 10,marginTop:10 }}
                  type="primary"
                  size="small"
                  icon="plus"
                  onClick={this.quoteAnswer}
                >
                  引用答案
                </Button>
              )}
            </div>
          </Col>
        </Row>

        <div>
          {answerArr.map((answer, index) => {
            return (
              <div key={index}>
                {!answer.isEdit ? (
                  <AnswerEdit
                    slotDetailArr={slotDetailArr}
                    answer={answer}
                    index={index}
                    callbackFromChild={this.callbackFromChild.bind(this)}
                    toAddSlotForSelect={this.toAddSlotForSelect.bind(this)}
                    toEditSlotByUnSelect={this.toEditSlotByUnSelect.bind(this)}
                    toOnEditQa={this.toOnEditQa.bind(this)}
                    onRef={ref => {
                      this.AnswerEdit = ref;
                    }}
                  ></AnswerEdit>
                ) : (
                  <AnswerBack
                    answer={answer}
                    index={index}
                    qaActiveKeys={qaActiveKeys}
                    callbackFromChild={this.callbackFromChild.bind(this)}
                    deleteQuestionFrom={this.deleteQuestionFrom}
                  ></AnswerBack>
                )}
                {
                  answer.answerQuestion ?
                    <div style={{marginTop:'10px'}}>引用自答案库：<span style={{color:'#11cbff'}}>{answer.answerQuestion}</span></div>
                    :
                    ''
                }
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

export default Answer;
